import { defineStore } from 'pinia'
import { ref } from 'vue'
import Api, { type ArticleDetail } from './api.ts'
import router from './router/index.js'

const useStore = defineStore(
  'store',
  () => {
    const page = ref(1) // 页码
    const pagesize = ref(3) // 页面显示的数量
    const count = ref(0) // 文章数量
    const category_id = ref() // 分类
    const tag_id = ref() // 标签
    const categoryData = ref<any[]>([]) // 分类数据
    const tagData = ref<any[]>([]) // 标签数据
    const articleData = ref<any[]>([]) // 文章数据
    const articleDetail = ref<ArticleDetail>()
    const imageUrl = import.meta.env.VITE_API_URL + '/' // 图片地址

    // 获取分类数据
    const getCategoryData = async () => {
      let result = await Api.getCategory()
      categoryData.value = result
    }

    // 获取标签数据
    const getTagData = async () => {
      let result = await Api.getTag()
      tagData.value = result
    }

    // 获取文章数据
    const getArticleData = async () => {
      let result = await Api.getArticle(
        page.value,
        pagesize.value,
        category_id.value,
        tag_id.value
      )
      articleData.value = result.result
      count.value = result.count
    }

    // 分页
    const changePage = (newPage) => {
      page.value = newPage
      getArticleData()
    }

    // 选择分类
    const selectCategory = (key, keyPath) => {
      category_id.value = key
      getArticleData()
    }

    // 选择标签
    const selectTag = (key, keyPath) => {
      tag_id.value = key
      getArticleData()
    }

    // 回到首页
    const backHome = () => {
      router.push('/')
      page.value = 1
      pagesize.value = 3
      category_id.value = ''
      tag_id.value = ''
      getArticleData()
    }

    // 跳转详情页面
    const toDetail = (article_id: number) => {
      router.push(`article/${article_id}`)
    }

    // 获取具体文章数据
    const getArticleDetailData = async (article_id) => {
      let result = await Api.getArticleDetail(article_id)
      articleDetail.value = result
    }

    // 增加浏览量
    const addViewsData = async (article_id: number, newViews: number) => {
      await Api.addViews(article_id, newViews)
    }

    // 点赞
    const addGoodData = async (article_id: any, newGood: number) => {
      await Api.addGood(article_id, newGood)
    }

    return {
      page,
      pagesize,
      count,
      category_id,
      tag_id,
      categoryData,
      tagData,
      articleData,
      imageUrl,
      articleDetail,
      getCategoryData,
      getTagData,
      getArticleData,
      selectCategory,
      selectTag,
      changePage,
      backHome,
      toDetail,
      getArticleDetailData,
      addViewsData,
      addGoodData,
    }
  },
  {
    persist: true,
  }
)

export default useStore
